import 'dart:io';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zchope_student/beans/citybean.dart';
import 'package:zchope_student/beans/userInfoBean.dart';
import 'package:zchope_student/utils/encode.dart';
import 'package:zchope_student/beans/eventbean.dart';
import 'package:zchope_student/utils/mydio.dart';
import 'package:zchope_student/utils/utils.dart';

import '../apis.dart';
import '../const.dart';
import '../routes.dart';

class UserData extends StatefulWidget {
  @override
  _UserDataState createState() => _UserDataState();
}

class _UserDataState extends State<UserData> {
  Map<String, dynamic> dataUser = Map();
  Map<String, dynamic> dataBind = Map();
  SharedPreferences sharedPreferences;
  String memberBh = '';
  UserInfoBean _userInfoBean;
  String _photo = '';
  String _loginName = '';
  String _nickName = '';
  String _personNum = '';
  String loginName = '';
  var _cityPicked = '';
  var _cityPickedCode = '';
  var pickerCity;
  File _image = null;
  var _scaffoldkey = new GlobalKey<ScaffoldState>();

//  _memberInfo() async {
//    SharedPreferences sp = await SharedPreferences.getInstance();
//    memberBh = sp.getString('bh');
//    dataBind['memberBh'] = memberBh;
//    dataUser['memberBh'] = memberBh;
//    MyDio.getInstance().get(Apis.memberInfo + memberBh, (data) async {
//      print(data);
//      if (data['resultCode'] == 0) {
//        _userInfoBean = UserInfoBean.fromJson(data['record']);
//        _photo = _userInfoBean.photo != null ? _userInfoBean.photo : '';
//        _nickName =
//            _userInfoBean.nickName != null ? _userInfoBean.nickName : '';
//        dataUser['nickName'] = _nickName;
//        _loginName = _userInfoBean.loginName;
//        _personNum =
//            _userInfoBean.personNum != null ? _userInfoBean.personNum : '';
//        dataBind['areacode'] = _userInfoBean.areacode;
//        setState(() {});
//      }
//    });
//  }

  _intentImagePicker(String type) async {
    String route = '${Routes.myImagePicker}?type=$type';
    _image = await Routes.router.navigateTo(context, route,
        replace: false, transition: TransitionType.fadeIn);
  }

  _ImageView(imgPath) {
    if (imgPath == null) {
      return Center(
        child: Icon(
          Icons.person,
          color: Const.gold,
          size: 100,
        ),
      );
    } else {
      return Image.file(
        imgPath,
        width: 100,
        height: 100,
      );
    }
  }

  _setPersonNum() {
    return _personNum != null && _personNum != ''
        ? Text(
            _personNum,
            style: TextStyle(color: Colors.white, fontSize: 18),
          )
        : EditText(
            data: dataBind,
            name: 'personNum',
            labelText: '二代身份证号',
            value: _personNum,
          );
  }

  @override
  void initState() {
    //    _memberInfo();
    getMemberhb();
    _buildPickerCity();
    if(_cityPickedCode==null || _cityPickedCode==''){
        _getLocatedCode();
    }
  }

  _getLocatedCode() async{
    SharedPreferences sharedPreferences=await SharedPreferences.getInstance();
    _cityPicked = Utils.getInstance().getCityName(sharedPreferences.getString(Const.AREA_CODE));
    sharedPreferences.setString('areacode', sharedPreferences.getString(Const.AREA_CODE));
    dataBind['areacode'] = sharedPreferences.getString(Const.AREA_CODE);
  }

  _buildPickerCity() {
    pickerCity = Picker(
      headercolor: Const.black,
      containerColor: Const.black,
      backgroundColor: Const.black,
      adapter: PickerDataAdapter(data: _setPickerCities()),
      title: Text(
        '请选择',
        style: TextStyle(color: Const.gold),
      ),
      cancelText: '取消',
      cancelTextStyle: TextStyle(color: Const.gold),
      confirmText: '确定',
      confirmTextStyle: TextStyle(color: Const.gold),
      textStyle:  TextStyle(color: Const.gold),
      onConfirm: (Picker picker, List value) {
        setState(() {
          _cityPicked = Const.cities[value[0]].name;
          dataBind['areacode'] = Const.cities[value[0]].code;
          _cityPickedCode = Const.cities[value[0]].code;
          _saveCityAndCode(_cityPicked, _cityPickedCode);
          print(Const.cities[value[0]].code);
        });
      },
    );
  }

  _setPickerCities() {
    List<PickerItem<dynamic>> pickerItems = List();
    for (CityBean bean in Const.cities) {
      pickerItems.add(PickerItem(
          value: Icons.add,
          text: Text(bean.name,
              style: TextStyle(color: Const.gold))));
    }
    return pickerItems;
  }

  getMemberhb() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    _cityPicked = Utils.getInstance().getCityName(sp.get('areacode'));
    dataBind['memberBh'] = sp.getString('bh');
    dataUser['memberBh'] = sp.getString('bh');
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Const.bar,
      key: _scaffoldkey,
      appBar: AppBar(
        actions: <Widget>[
          GestureDetector(
            onTap: () {
              pickerCity.show(_scaffoldkey.currentState);
            },
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: SizedBox(
                height: 60,
                child: Center(
                  child: Text(
                    _cityPicked,
                    style: TextStyle(fontSize: 15, color: Const.gold),
                  ),
                ),
              ),
            ),
          )

//          IconButton(
//            onPressed: () {
//              pickerCity.show(_scaffoldkey.currentState);
//            },
//            icon: Icon(
//              Icons.arrow_back_ios,
//              color: Const.gold,
//            ),
//          ),
        ],
        backgroundColor: Const.bar,
        centerTitle: true,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 33),
            child: Column(
              children: <Widget>[
                GestureDetector(
                    onTap: () {
                      showModalBottomSheet(
                          context: context,
                          builder: (BuildContext context) {
                            return Column(
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                ListTile(
                                  title: Text('相机'),
                                  onTap: () {
                                    Navigator.pop(context);
                                    _image = _intentImagePicker(Const.Camera);
                                  },
                                ),
                                ListTile(
                                  title: Text('相册'),
                                  onTap: () {
                                    Navigator.pop(context);
                                    _image = _intentImagePicker(Const.Picture);
                                  },
                                )
                              ],
                            );
                          });
                    },
                    child: _ImageView(_image)),
                _setPersonNum(),
                EditText(
                  data: dataUser,
                  name: 'nickName',
                  labelText: '昵称',
                  value: _nickName,
                ),
              ],
            ),
          ),
          MaterialButton(
            height: 68,
            minWidth: MediaQuery.of(context).size.width,
            elevation: 0,
            onPressed: () {
              if (dataBind['areacode'] == null) {
                Utils.getInstance().showSnackBar(_scaffoldkey, '请先选择城市');
                 return;
              }

              MyDio.getInstance().post(Apis.bind, (data) async {
                print(dataBind);
                Utils.getInstance().showSnackBar(_scaffoldkey, data['msg']);
                if (data['resultCode'] == 0) {
                  print('成功');
                  SharedPreferences sp = await SharedPreferences.getInstance();
                  sp.setString(Const.PERSON_NUM, dataBind['personNum']);
                  sp.setString(Const.AREA_CODE, _cityPickedCode);
                  eventBus.fire(EventBean(title:Const.EVENT_BIND));
                  Navigator.pop(context);
                }
              }, params: dataBind);

              Encode.image2Base64(_image).then((data) {
                print(data);
                dataUser['photo'] = data;
                MyDio.getInstance().post(Apis.info, (data) async {
                  Utils.getInstance().showSnackBar(_scaffoldkey, data['msg']);
                  if (data['resultCode'] == 0) {
                    Navigator.pop(context);
                  }
                }, params: dataUser);
              });
            },
            child: Text(
              "确    认",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
            color: Const.gold,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    bottomRight: Radius.circular(30))),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    MyDio.getInstance().clearInstance();
  }

  void _saveCityAndCode(String cityPicked, String cityPickedCode) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString('cityName', cityPicked);
    sp.setString('areacode', cityPickedCode);
  }
}

class EditText extends StatelessWidget {
  final data;
  final name;
  final labelText;
  final value;
  final icon;

  const EditText(
      {Key key, this.data, this.name, this.labelText, this.value, this.icon})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: TextEditingController.fromValue(TextEditingValue(
          text: value,
          selection: TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream, offset: value.length)))),
      onChanged: (value) {
        data[name] = value;
      },
      style: TextStyle(fontSize: 18, color: Colors.white),
      decoration: InputDecoration(
//        icon: Icon(icon,color:Const.gold,),
        labelText: labelText,
        labelStyle: TextStyle(color: Const.grey, fontSize: 18),
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(
          color: Colors.white,
          width: 1,
        )),
        enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(
          color: Colors.white,
          width: 1,
        )),
      ),
    );
  }
}
